import {
	fabric
} from "fabric";

class CanvasStateManager {
	/**
	 * 画布
	 */
	canvas;

	/**
	 * 状态
	 */
	states = [];

	/**
	 * 取消的状态
	 */
	cancelled = [];
	
	/**
	 * 取消的状态
	 */
	isRecord = true;

	/**
	 * 初始化
	 * @param {Object} canvas
	 */
	constructor(canvas) {
		this.canvas = canvas;
		this.canvas.on({
			"object:added": () => {
				this._recordCanvasState();
			},
			"object:modified": () => {
				this._recordCanvasState();
			},
		})
	}

	/**
	 * 回退
	 */
	undo() {
		if(this.states.length > 0){
			this.cancelled.push(this.states.pop());
			
			if (this.states.length > 0) {
				this._loadCanvasState(this.states.length - 1);
			} else  {
				this.canvas.clear();
				this.states = [];
			}
		}
	}

	/**
	 * 恢复
	 */
	redo() {
		if (this.cancelled.length > 0) {
			this.states.push(this.cancelled.pop());
			this._loadCanvasState(this.states.length - 1);
		}
	}
	
	/**
	 * 恢复
	 */
	clear() {
		vk.confirm('确认要清空画布吗？', '提示', '确定', '取消', res => {
			if (res.confirm) {
				this.canvas.clear();
				this.states = [];
				this.cancelled = [];
			}
		});
	}

	/**
	 * 记录画布状态
	 */
	_recordCanvasState() {
		if(this.isRecord){
			const canvasAsJson = JSON.stringify(
				this.canvas.toJSON(["id", "selectable", "hasControls"])
			);
			this.states.push(canvasAsJson);
			this.cancelled = [];
		}
	}

	/**
	 * 加载画布状态
	 */
	_loadCanvasState(index) {
		this.isRecord = false;
		this.canvas.loadFromJSON(JSON.parse(this.states[index]), () => {
			this.canvas.renderAll();
			this.isRecord = true;
		});
	}
}

module.exports = CanvasStateManager